<template>
  <h1>详情页</h1>
  <h3>{{weibo.nickname}}说:{{weibo.content}}</h3>
  <p>发布于:{{weibo.created}}</p>
  <hr>
  <h4>评论相关</h4>
  <input type="text" placeholder="请输入评论内容" v-model="c.content">
  <input type="button" value="发评论" @click="postComment">
  <div v-for="c in commentArr">
    <h5>{{c.nickname}}评论说:{{c.content}}</h5>
    <p style="font-size: 12px;margin: 0;color: #666">{{c.created}}</p>
  </div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import router from "@/router";
//发布评论
const  c=ref({content:""})
const postComment=()=>{
  //评论内容 用户id 微博id
  let user=localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录");
    router.push('/login');
    return;
  }
  //获取用户id
  c.value.userId=user.id;
  //获取微博id
  c.value.weiboId=weibo.value.id;
  axios.post('http://localhost:8080/v1/comments/add-new',c.value)
  .then((response)=>{
    if (response.data.code==1){
      alert("评论完成!");
      loadComment(weibo.value.id);
    }
  })
}


//获取评论
const commentArr=ref([])
const loadComment=(weiboId)=>{
  axios.get('http://localhost:8080/v1/comments/'+weiboId+'/list')
      .then((response)=>{
        if (response.data.code==1){
          commentArr.value=response.data.data;
        }
      })
}

//响应式变量必须定义在stript标签的跟目录下,不能定义在某个方法的里面
//响应式变量如果是一个变量,不能为null,用{}表示无数据
const weibo = ref("");
onMounted(()=>{

  //从地址栏中获取id
  let id = new URLSearchParams(location.search).get('id');
  //请求微博评论的数据
  loadComment(id);
  //通过id查询微博详情内容
  axios.get('http://localhost:8080/v1/weibos/'+id).then((response)=>{
    if (response.data.code==1){
      console.log(response.data.data);
      weibo.value = response.data.data;
    }
  })

})



</script>